<?php


namespace addons\csmitsm\controller;

use addons\csmitsm\library\sdnode\xstack\utils\XsJsonUtils;
use addons\csmitsm\library\xcore\xcore\base\XcAAdminApi;
use addons\csmitsm\library\xcore\xcore\utils\XcDaoUtils;
use addons\csmitsm\library\xcore\xcore\utils\XcRequestUtils;
use addons\csmitsm\library\xcore\xcflow\utils\XcformFieldsUtils;
use addons\csmitsm\library\xcore\xcflow\utils\XcformXcchartUtils;
use addons\csmitsm\library\xcore\xcore\utils\XcDashboardUtils;
use addons\csmitsm\library\xcore\xcore\utils\XcDatabaseUtils;
use addons\csmitsm\library\xcore\xcore\utils\XcTransactionUtils;

class XcXcflowchartpage extends XcAAdminApi
{
    protected $staticFieldsJsonString = null;
    protected $xcformDao = null;
    protected $xcformFieldDao = null;
    protected $xcformidFieldname = null;

    public function xinit()
    {
        $this->xcformDao = new \app\admin\model\csmitsm\Xcflowchartpage();
        $this->xcformFieldDao = new \app\admin\model\csmitsm\Xcflowchartpagejson();
        $this->xcformidFieldname = 'xcflowchartpage_id';
        $this->staticFieldsJsonString = "[]";
    }

    private function _getFormgenerateFields($xcform_id)
    {
        $fieldList = XcDaoUtils::getListBySql($this->xcformFieldDao, [
            [$this->xcformidFieldname, "=", $xcform_id]
        ], null, "weigh asc ");

        $fields = [];
        if (count($fieldList) > 0) {
            foreach ($fieldList as $item) {
                // $fieldjsonObj =  empty($item->fieldjson) ? [] : json_decode($item->fieldjson, true);
                $fieldjsonObj = XsJsonUtils::stringToJson($item->fieldjson);

                $fieldjsonObj['id'] = $item->id;
                $fields[] = $fieldjsonObj;
            }
        }
        // else {
        //     $fields = json_decode($this->staticFieldsJsonString, true);
        // }
        return $fields;
    }

    public function getXcFormFields()
    {
        $xcform_id = XcRequestUtils::get("xcform_id", true);
        $fields = $this->_getFormgenerateFields($xcform_id);
        $xcform = XcDaoUtils::getRowById($this->xcformDao, $xcform_id);

        $rr = $this->_getXcFormFields();
        if ($rr === true) {
            $this->success(null, [
                'fields' => $fields,
                "needPublish" => XcformFieldsUtils::needPublish($this->xcformFieldDao, $this->xcformidFieldname, $xcform_id),
            ]);
        }
    }

    protected function _getXcFormFields()
    {
        return true;
    }

    public function saveXcFormFields()
    {
        $xcform_id = XcRequestUtils::get("xcform_id", true);
        $fieldsjson = XcRequestUtils::requestBodyJson();

        $result = XcTransactionUtils::service(function () use ($xcform_id, $fieldsjson) {
            // createOrUpdate xcformfield_table
            $vmodels = [];
            if (true) {
                // $weighcount = count($fieldsjson);
                foreach ($fieldsjson as $index => $item) {
                    $vmodel = $item['__vModel__'];

                    $row = XcDaoUtils::getRowBySql($this->xcformFieldDao, [
                        [$this->xcformidFieldname, '=', $xcform_id],
                        ['vmodel', '=', $vmodel]
                    ]);
                    $pp = [
                        $this->xcformidFieldname => $xcform_id,
                        'title' => isset($item['xcchart_base_xctitle']['value']) ? $item['xcchart_base_xctitle']['value'] : null,
                        'fieldtag' => $item['__config__']['tag'],
                        'weigh' => $index,
                        'fieldjson' => XsJsonUtils::jsonToString($item),
                        'haspublish' => 'N'
                    ];

                    if ($row) {
                        $row->save($pp);
                    } else {
                        $pp['vmodel'] = $vmodel;
                        $row = $this->xcformFieldDao->create($pp);
                    }
                    $vmodels[] = $vmodel;
                }
            }
            // drop column from xcformfield_table
            if (true) {
                // var_dump($fieldIds);
                $list = XcDaoUtils::getListBySql($this->xcformFieldDao, [
                    [$this->xcformidFieldname, '=', $xcform_id],
                    ['vmodel', 'not in', $vmodels]
                ]);
                foreach ($list as $item) {
                    XcDaoUtils::getRowById($this->xcformFieldDao, $item->id)->save([
                        'status' => 'hidden',
                    ]);
                }
            }
        });


        $this->success(null, ['needPublish'=>true]);
    }

    public function publishXcForm()
    {
        $xcform_id = XcRequestUtils::get("xcform_id", true);
        XcTransactionUtils::service(function () use ($xcform_id) {
            $xcform = XcDaoUtils::getRowById($this->xcformDao, $xcform_id);

            if (true) {
                $xcflowfield = [];

                $fieldList = XcDaoUtils::getListBySql($this->xcformFieldDao, [
                    [$this->xcformidFieldname, "=", $xcform_id]
                ], null, "weigh asc");
                foreach ($fieldList as $item) {
                    $xcflowfield[] = [
                        'title' => $item->title,
                        'fieldjson' => $item->fieldjson,
                        'fieldtag' => $item->fieldtag,
                    ];
                    $item->save(['haspublish' => 'Y']);
                }
                $xcform = XcDaoUtils::getRowById($this->xcformDao, $xcform_id);
                $xcform->save([
                    'xcfieldjson' => XsJsonUtils::jsonToString($xcflowfield),
                    'updatetime' => time(),
                ]);
            }
        });
        $this->success(null);
    }

    public function getXcchartOptions()
    {
        $body = XcRequestUtils::requestBodyJson();
        $xcchart_data_dim = $body['xcchart_data_dim'];
        $xcchart_data_facts = $body['xcchart_data_facts'];

        // $dims = XcDatabaseUtils::getListByPuresql($xcchart_data_dim['sql']);
        // $dimcodes = XcDaoUtils::getValuesFromList($dims, "dimcode");
        // $dimlabels = XcDaoUtils::getValuesFromList($dims, "dimlabel");

        // $facts = [];
        // foreach ($xcchart_data_facts['values'] as $xcchart_data_fact) {
        //     $sql = "select * from (" . $xcchart_data_fact['sql'] . ") xcchartdata where xcchartdata.dimcode in (" . join(',', $dimcodes) . ")";
        //     $datas = XcDatabaseUtils::getListByPuresql($sql);
        //     $facts[] = XcDashboardUtils::adjustLineData($dimcodes, $datas, "dimcode", "fact");
        // }

        // // remove zero dims
        // if ($xcchart_data_dim['hiddenZeroLabel']) {
        //     [$dimlabels, $facts] = XcDashboardUtils::hiddenZeroLabel($dimlabels, $facts);
        // }
        [$dimlabels, $facts] = XcformXcchartUtils::getXcchartOptions($xcchart_data_dim, $xcchart_data_facts);

        $this->success(null, [
            'dimlables' => $dimlabels,
            'facts' => $facts
        ]);
    }


}
